import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: GodK
 * Date: 2024-07-25
 * Time: 21:25
 */

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;

    private long time;

    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime(){
        return time;
    }

    public void run (){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask current = queue.peek();
                        if (System.currentTimeMillis() >= current.getTime()) {
                            current.run();
                            queue.poll();
                        } else {
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}
public class Main {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> {
            System.out.println("hello 3000");
        }, 3000);
        myTimer.schedule(() -> {
            System.out.println("hello 2000");
        }, 2000);
        myTimer.schedule(() -> {
            System.out.println("hello 1000");
        }, 1000);
        System.out.println("程序开始执行");
    }
}
